#include "visit.h"

void visitConstDecl(ASTNode *ctx, SymbolTable *s, Module *m, BasicBlock *bb);
void const_visitChildren(ASTNode *ctx, SymbolTable* s, Module* m, string &type, string &var_name, variant<int, std::string> &data);
void visitBType(ASTNode *ctx, string &type);
void visitIdent(ASTNode *ctx, string &var_name);
void visitNumber(ASTNode *ctx, variant<int, std::string> &data);

void visitConstDecl(ASTNode *ctx, SymbolTable *s, Module *m, BasicBlock *bb) {
    // 处理常量声明
    string type = "int";
    string var_name = "constVar";
    std::variant<int, std::string> data;
    const_visitChildren(ctx, s, m, type, var_name, data);

    if (s->lookup(var_name) != nullptr) {
        cout << "常量名" << var_name << "重复命名" << endl;
        throw std::invalid_argument("常量名重复命名");
    }

    int value;
    if (auto* p = std::get_if<int>(&data)) {
        value = *p;
    } else if (auto* p = std::get_if<std::string>(&data)) {
        string lookup_name = removeRedundantBrackets(*p);
        Symbol* symbol = s->lookup(lookup_name);
        if (symbol == nullptr) {
            cout << "变量名" << lookup_name << "未命名" << endl;
            throw std::invalid_argument("变量名未命名");
        }
        value = symbol->value;
    }

    Type* ir_type = m->get_int32_type();
    GlobalVariable* gv = GlobalVariable::create(var_name, m, ir_type, true, ConstantInt::get(value, m));
    s->addSymbol(var_name, CONST, type, value, gv);
}
void const_visitChildren(ASTNode *ctx, SymbolTable* s, Module* m, string &type, string &var_name, variant<int, std::string> &data) {

    for(int i=0; i < (int)ctx->children.size(); i++){
        //children.size()得到ctx节点的子节点数
        //访问bType子结点获取变量类型
        // cout << "ctx->children[i]->type : " << ctx->children[i]->type << endl;
        if(ctx->children[i]->type == "bType"){
            // cout << "Hello bType" << endl;
            visitBType(ctx->children[i], type);
        }
        //访问valDef子结点获取变量名和初始数值
        else if(ctx->children[i]->type == "constDef"){
            ASTNode *child = ctx->children[i];
            for(int j=0; j < (int)child->children.size(); j++){
                if(child->children[j]->type == "Ident"){
                    visitIdent(child->children[j], var_name);
                }
                if(child->children[j]->type == "constInitVal"){
                    visitNumber(child->children[j], data);
                }
                
            }
        }
    }


    return;
}